import React, { useState } from 'react';
import { request, useNavigate } from '@umijs/max';
import { CaretDownOutlined } from '@ant-design/icons';
import { Avatar, Dropdown, Space, Typography, Modal, Form, Input, message } from 'antd';
const { Text } = Typography;

const items = [
  { key: '2', label: '修改密码' },
  { key: '1', label: '退出登录' },
];

const UserAvatar = ({ userInfo }) => {
  let navigate = useNavigate();
  const [form] = Form.useForm();
  const {userName, nickName, phonenumber} = userInfo;
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handleOk = () => {
    form.validateFields().then(async (values) => {
      await request(
        '/resetPwd',
        { method: 'PUT', data: values }
      );
      handleCancel();
      message.success('密码修改成功');
      onClick({key: "1"})
    })
  }

  const onClick = ({ key }) => {
    if(key === '1') {
      localStorage.removeItem('token');
      navigate('/login', { replace: true });
    }else if(key === '2') {
      setIsModalOpen(true);
      form.resetFields();
    }
  };

  return (
    <>
      <Dropdown
        placement="bottomRight"
        trigger="click"
        arrow
        menu={{
          items,
          onClick,
        }}
      >
        <Space
          style={{marginRight: 16, cursor: 'pointer'}}
          direction="horizontal"
          align="center"
          size={4}>
          <Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=3" />
          <Text>{userName}</Text>
          <CaretDownOutlined />
        </Space>
      </Dropdown>
      <Modal
        title="修改密码"
        width={600}
        maskClosable={false}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}>
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          initialValues={{
            password: "",
            confirm: "",
          }}
          autoComplete="off"
        >
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码!' }]}
            hasFeedback>
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="confirm"
            label="确认密码"
            dependencies={['password']}
            hasFeedback
            rules={[
              { required: true, message: '请输入密码!' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致!'));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
export default UserAvatar;
